#include "stdio.h"
#include "stdint.h"
#include "string.h"

#include "ff.h"

#include "DevicesKey.h"
#include "DevicesQueue.h"
#include "NesSystem.h"

#include "DriverLcd.h"
#include "DriverFile.h"
#include "DriverImage.h"
#include "DriverMenu.h"


/* 当前选项 */
int32_t g_uiOption = 0;
int32_t g_uiOptionLast = 100;

extern char g_cNesRomPath[64];


int8_t cMenuFileShow(char *pcPath, int32_t iNo)
{
    static int32_t st_iNoLast;
    FILINFO fno;
    DIR dir;
    FRESULT res;
    int32_t iStart = (iNo / 10) * 10, iEnd = iStart + 9, i = 0, y = 56;

    if((res = f_opendir(&dir, pcPath)) == FR_OK)
    {
        if((st_iNoLast / 10) != (iNo / 10))
        {
            st_iNoLast = iNo;

            vLcdClear(0, 56, 320, 216, RED);
        }

        while(1)
        {
            res = f_readdir(&dir, &fno);
            if (res != FR_OK || fno.fname[0] == 0)
                break;

            /* 文件 */
            if((fno.fattrib & AM_DIR) == 0)
            {
                if(i >= iStart)
                {
//                    printf("File: %s/%s, size: %d\n", pcPath, fno.fname, fno.fsize);
                    if(i == iNo)
                    {
                        memset(g_cNesRomPath, 0, sizeof(g_cNesRomPath));
                        memcpy(g_cNesRomPath, "./NES/ROM/", strlen("./NES/ROM/"));
                        memcpy(&g_cNesRomPath[strlen(g_cNesRomPath)], fno.fname, strlen(fno.fname));
                        cLcdStringShow(0, y, WHITE, RED, fno.fname);
                    }
                    else
                        cLcdStringShow(0, y, BLACK, RED, fno.fname);

                    y += 16;
                }

                /* 退出显示 */
                if((++i) > iEnd)
                    break;
            }
        }

        res = f_closedir(&dir);
    }

    return res;
}

int8_t cMenuInit(void)
{
    NesInfoType *ptyeNesInfo = ptyeNesInfoGet();
    KeyType typeKey;

    if(enumQueuePopDatas(&g_TypeQueueKeyInput, &typeKey, sizeof(typeKey)) == queueNormal)
    {
        if((typeKey.state == keyShort) || (typeKey.state == keyContinuous))
        {
            if(typeKey.valueDown == KEY_UP)
                g_uiOption -= 1;
            else if(typeKey.valueDown == KEY_DOWN)
                g_uiOption += 1;
            else if(typeKey.valueDown == KEY_LEFT)
                g_uiOption -= 10;
            else if(typeKey.valueDown == KEY_RIGHT)
                g_uiOption += 10;
            else if(typeKey.valueDown == KEY_START)
                ptyeNesInfo->runing = 1;
        }

        g_uiOption = g_uiOption < 0 ? 0 : g_uiOption;
    }

    if(g_uiOptionLast != g_uiOption)
    {
        g_uiOptionLast = g_uiOption;

        cMenuFileShow("./NES/ROM/", g_uiOption);
    }

    return 0;
}
